package org.wisigoth.chat.swing.accountframe;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.JList;
import javax.swing.ListModel;

import org.wisigoth.chat.client.Contact;
import org.wisigoth.chat.client.Presence;
import org.wisigoth.chat.swing.WisigothController;

public class ContactListController implements ActionListener {

	private WisigothController parent;

	private ContactListFrame contactListFrame;

	public ContactListController(WisigothController parent) {
		this.parent = parent;
	}

	public void setContactListVisible(boolean visible) {
		this.getContactListFrame().setVisible(visible);
	}

	private ContactListFrame getContactListFrame() {
		if (this.contactListFrame == null) {
			this.contactListFrame = new ContactListFrame(this.parent);
			this.contactListFrame.setTitle(this.parent.getSession().whoAmI().getNickName());
			this.contactListFrame.getPresenceComboBox().addActionListener(this);
			this.contactListFrame.getQuitmenuItem().addActionListener(this);
			this.contactListFrame.getJList().addMouseListener(
					new ActionJList(this.contactListFrame.getJList()));

		}
		return this.contactListFrame;
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == this.contactListFrame.getPresenceComboBox()) {
			this.parent.getSession().setPresence(
					(Presence) this.contactListFrame.getPresenceComboBox()
							.getSelectedItem());

			this.contactListFrame.setIconImage(this.parent.getSession()
					.getPresence().getPresenceImage().getImage());
		} else if (e.getSource() == this.contactListFrame.getQuitmenuItem()) {
			this.parent.getSession().quitWisigoth();
		}
	}
	
	public ContactListFrame getContactList() {
		return this.contactListFrame;
	}

	class ActionJList extends MouseAdapter {
		protected JList list;

		public ActionJList(JList l) {
			this.list = l;
		}

		@Override
		public void mouseClicked(MouseEvent e) {
			if (e.getClickCount() == 2) {
				int index = this.list.locationToIndex(e.getPoint());
				ListModel listModel = this.list.getModel();
				Contact contact = (Contact) listModel.getElementAt(index);
				this.list.ensureIndexIsVisible(index);
				ContactListController.this.parent.openChatSession(contact);
				
				
			}
		}

	}
}
